<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/8/25
 * Time: 10:45
 */

namespace app\logic\index\sms;


use app\common\lib\Common;
use app\common\lib\Sms;
use app\exception\IndexException;
use app\logic\BaseLogic;
use support\Cache;

class SmsLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
//        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return  new self();
    }

    public function sendSmsAuthCode($param)
    {
        if(Common::checkMobile($param['mobile'])==false){
            throw new IndexException(4020,'手机号错误');
        }

        $cache = Cache::get('sms_auth_code_'.$param['auth_type'].'_'.$param['mobile']);
        if($cache && (time()-$cache['time'])<30){
            throw new IndexException(4020,'已经发送，请勿频繁发送');
        }


        $config = config('param.aliyun_sms');
        $code = Common::randString(6,1);
        $params = [
            'signName'=>$config['sign_name'],
            'templateCode'=>$config['template_code'],
        ];
        $sms = (new Sms($config['access_key_id'],$config['access_key_secret']));
        $result = $sms->sendAuthCode($param['mobile'],$code,$params);

        if(!empty($result['Code']) && $result['Code']=='OK'){
            Cache::set('sms_auth_code_'.$param['auth_type'].'_'.$param['mobile'],['code'=>$code,'time'=>time()],120);

            return $result;
        }elseif(!empty($result['Code']) && $result['Code']=='isv.BUSINESS_LIMIT_CONTROL'){
            throw new IndexException(4020,'今日发送次数已达上限');
        }

        throw new IndexException(4020,'发送错误');
    }
}